// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = _.aggregate

// 每页显示的数量
const PAGE_SIZE = 20

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const page = event.page || 1

  try {
    // 获取总玩家数和用户排名
    const rankResult = await db.collection('users')
      .aggregate()
      .match({
        highScore: _.gt(0)  // 只统计有分数的用户
      })
      .sort({
        highScore: -1,  // 按分数降序排序
        updateTime: 1   // 同分时按更新时间升序排序
      })
      .group({
        _id: null,
        users: $.push({
          openid: '$openid',
          nickname: '$nickname',
          avatarUrl: '$avatarUrl',
          highScore: '$highScore'
        })
      })
      .end()

    const rankList = rankResult.list[0]?.users || []
    const totalPlayers = rankList.length

    // 计算用户排名
    let myRank = 0
    let myData = null
    for (let i = 0; i < rankList.length; i++) {
      if (rankList[i].openid === openid) {
        myRank = i + 1
        myData = rankList[i]
        break
      }
    }

    // 获取分页数据
    const skip = (page - 1) * PAGE_SIZE
    const pageData = rankList.slice(skip, skip + PAGE_SIZE)

    // 处理排行榜数据
    const formattedRankList = pageData.map((user, index) => ({
      rank: skip + index + 1,
      openid: user.openid,
      nickname: user.nickname,
      avatarUrl: user.avatarUrl,
      highScore: user.highScore,
      isMe: user.openid === openid
    }))

    return {
      success: true,
      data: {
        rankList: formattedRankList,
        myRank,
        myData,
        totalPlayers,
        currentPage: page,
        totalPages: Math.ceil(totalPlayers / PAGE_SIZE),
        hasMore: skip + PAGE_SIZE < totalPlayers
      }
    }
  } catch (err) {
    return {
      success: false,
      error: err
    }
  }
}